/*
    Copyright 2007-2008 Adrien Guillon.  All Rights Reserved.

    This file is part of TBB Community Code. 

    TBB Community Code is free software; you can redistribute it
    and/or modify it under the terms of the GNU General Public License
    version 2 as published by the Free Software Foundation.

    TBB Community Code is distributed in the hope that it will be
    useful, but WITHOUT ANY WARRANTY; without even the implied warranty
    of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with TBB Community Code; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

    As a special exception, you may use this file as part of a free software
    library without restriction.  Specifically, if other files instantiate
    templates or use macros or inline functions from this file, or you compile
    this file and link it with other files to produce an executable, this
    file does not by itself cause the resulting executable to be covered by
    the GNU General Public License.  This exception does not however
    invalidate any other reasons why the executable file might be covered by
    the GNU General Public License.
*/

#ifndef __TCC_owner_container_H
#define __TCC_owner_container_H

#include <algorithm>
#include <set>

#include <tbb/concurrent_vector.h>
#include <tbb/spin_mutex.h>

#include <boost/checked_delete.hpp>

#include <tcc/stl_container_types/set.h>


namespace tcc {

/**
 * A container for owned objects, storing pointers to them.  This container
 * "owns" the objects pointed to, and will call delete on each of them when
 * this object is destructed.
 *
 * The goal of this class is to provide a method of storing objects in an
 * exception safe manner, without using smart pointers.
 *
 * Instantiate the template with the type of object it will contain, not
 * with pointers itself.  For instance, owning_container<Object> not
 * owning_container<Object*>.
 *
 * The deleter template argument is for a function object which
 * implements void operator()(T* x), and deletes the object.  By
 * default, normal C++ delete is called.
 */

template <typename T, typename deleter = boost::checked_deleter<T>, typename Container = typename cache_aligned_set<T*>::set >
class owning_container 
{
public:
    typedef Container container_type;

    /**
     * Construct an empty owning_container 
     */
    owning_container() { }

    /**
     * The destructor calls delete on all contained object pointers.
     *
     * TODO: Should the destructor use the mutex?
     */
    ~owning_container()
    {
        if(!empty())
        {
            deleteAll();
        }
    }

    /**
     * Takes ownership of an object.  This container will now own the object,
     * and is responsible for the destruction of the object unless the user
     * destroys it themselves with delete_member(x) or steal_member(x).  
     *
     * This function is thread safe.
     */
    void giveOwnership(T* x)
    {
        { // BEGIN MUTEX
            tbb::spin_mutex::scoped_lock lock(_ownedObjectsMutex);
            _ownedObjects.insert(x);
        } // END MUTEX
    }


    /**
     * Take ownership of an object away from this container.  The object
     * will no longer be owned by this container, and a pointer will be
     * returned to the user.
     *
     * This function is thread safe.
     */
    T* takeOwnership(T& x)
    {
        typename container_type::iterator i;
        T* objectToRemove;

        { // BEGIN MUTEX
            
            tbb::spin_mutex::scoped_lock lock(_ownedObjectsMutex);
             i = std::remove(_ownedObjects.begin(), _ownedObjects.end(), &x);
             objectToRemove = *i;
             _ownedObjects.erase( i, _ownedObjects.end() );
        } // END MUTEX

        return objectToRemove;
    }

    /**
     * Call delete on an object owned by this container.  The object deleted
     * is removed from ownership.
     *
     * This function is thread safe.
     */
    void deleteMember(T& x)
    {
        T* objectToDelete;
        objectToDelete = takeOwnership(x);
        _deleter(objectToDelete);
    }

    /**
     * Call delete on all objects owned by this container.  All objects
     * deleted are removed from ownership.  A mutex is used to govern
     * access of internal data structures.  This is the same function which
     * is called by the destructor.
     *
     * This function is thread safe.
     */
    void deleteAll()
    {
        { // BEGIN MUTEX
            
            tbb::spin_mutex::scoped_lock lock(_ownedObjectsMutex);

            std::for_each(_ownedObjects.begin(), _ownedObjects.end(), _deleter);

            _ownedObjects.clear();

        } // END MUTEX
    }

    /**
     * Check if this container owns anything.
     *
     * This function is thread safe.
     *
     * @return true if there are no objects owned, false otherwise.
     */
    bool empty() const
    {
        return _ownedObjects.empty();
    }

private:
    /**
     * Copying an owned object is not permitted.
     */
    owning_container(const owning_container& x);

    /**
     * Actual object container.
     */
    container_type _ownedObjects;

    /**
     * Instantiate an actual instance of the deleter.
     */
    deleter _deleter;
    
    /**
     * Mutex for the internal data structure.
     */
    tbb::spin_mutex _ownedObjectsMutex;
};

} // END NAMESPACE tcc

#endif

